import axios from 'axios';

const api = axios.create({
    baseURL: 'http://127.0.0.1:4523/m1/5546336-5223294-default',
});

// 请求拦截器：添加 token
api.interceptors.request.use(config => {
    const token = localStorage.getItem('access_token');
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
});

// 响应拦截器：处理 token 过期
api.interceptors.response.use(
    response => response,
    async error => {
        const originalRequest = error.config;

        if (error.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;

            try {
                // 调用刷新令牌接口
                const response = await axios.post('/auth/refresh');
                const { access_token } = response.data;
                
                // 更新本地存储的访问令牌
                localStorage.setItem('access_token', access_token);
                
                // 重试原始请求
                originalRequest.headers.Authorization = `Bearer ${access_token}`;
                return api(originalRequest);
            } catch (refreshError) {
                // 刷新令牌也失败，需要重新登录
                localStorage.removeItem('access_token');
                window.location.href = '/login';
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error);
    }
);

export default api;

// pages/Login.js
async function handleLogin(username, password) {
    try {
        const response = await api.post('/auth/login', {
            username,
            password
        });
        
        // 保存访问令牌到 localStorage
        localStorage.setItem('access_token', response.data.access_token);
        
        // 刷新令牌已自动保存在 Cookie 中
        
        // 跳转到主页
        window.location.href = '/dashboard';
    } catch (error) {
        console.error('登录失败:', error);
    }
}